package com.ship.dispatch.service.fob.impl;/*
 *@title SpFobZfzzcdyfkServiceImpl
 *@description
 *@author yl
 *@create 2023/12/17 0017
 */

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.utils.StringUtils;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.core.utils.DateUtil;
import com.ship.common.security.utils.SecurityUtils;
import com.ship.dispatch.bean.SpDispatchSchemeDetail;
import com.ship.dispatch.bean.SpDispatchSchemeExecute;
import com.ship.dispatch.bean.fob.*;
import com.ship.dispatch.bean.orderPay.*;
import com.ship.dispatch.bo.orderPay.SpPaymentOrderBO;
import com.ship.dispatch.bo.orderPay.SpPaymentOrderDetailBO;
import com.ship.dispatch.bpm.service.ProcessInstanceService;
import com.ship.dispatch.bpm.service.TaskService;
import com.ship.dispatch.bpm.utils.CalculateDateUtil;
import com.ship.dispatch.bpm.utils.JsonUtils;
import com.ship.dispatch.bpm.utils.TemplateParamUtils;
import com.ship.dispatch.bpm.vo.ManageEntityVo;
import com.ship.dispatch.bpm.vo.dto.BpmTaskDto;
import com.ship.dispatch.mapper.fob.SpFobZfzzcdyfkMapper;
import com.ship.dispatch.mapper.fob.SpFobZzcbdlMapper;
import com.ship.dispatch.mapper.orderPay.ConFilesMapper;
import com.ship.dispatch.mapper.orderPay.ConShippingAgencyMapper;
import com.ship.dispatch.mapper.orderPay.SpFundManageMapper;
import com.ship.dispatch.service.SpDispatchSchemeDetailService;
import com.ship.dispatch.service.SpDispatchSchemeExecuteService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.dispatch.service.fob.SpFobTemplateService;
import com.ship.dispatch.service.fob.SpFobZfzzcdyfkService;
import com.ship.dispatch.service.fob.SpFobZzcbdlService;
import com.ship.dispatch.service.orderPay.SpPaymentOrderService;
import com.ship.dispatch.util.WordUtil;
import com.ship.system.api.BpmInstanceService;
import com.ship.system.api.RemoteUserService;
import com.ship.system.api.domain.SysUser;
import liquibase.pro.packaged.E;
import liquibase.pro.packaged.S;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.time.*;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SpFobZfzzcdyfkServiceImpl extends FobBaseServiceImpl<SpFobZfzzcdyfkMapper, SpFobZfzzcdyfk> implements SpFobZfzzcdyfkService {
    @Autowired(required = false)
    SpFobZfzzcdyfkMapper mapperapper;

    @Autowired
    SpFobFileRecordService spFobFileRecordService;

    @Autowired
    SpDispatchSchemeExecuteService schemeDetailService;

    @Autowired
    SpFobTemplateService spFobTemplateService;

    @Autowired
    SpFobZzcbdlService spFobZzcbdlService;

    @Override
    public void updateEntity(ManageEntityVo manageEntityVo, String json) {
        SpFobZfzzcdyfk object = JsonUtils.jsonToObject(json,SpFobZfzzcdyfk.class);
        SpFobZfzzcdyfk his = mapperapper.selectOne(new LambdaQueryWrapper<SpFobZfzzcdyfk>().eq(SpFobZfzzcdyfk::getProceeInstanceId,manageEntityVo.getProcessInstanceId()).ne(SpFobZfzzcdyfk::getStatus,-2));
        if(manageEntityVo.getOperationType()==1) {
            object.setStatus(1);
        }
        if(his==null){ // 新增
            object.setSchemeDetailId(manageEntityVo.getSchemeDetailId());
            object.setTaskId(manageEntityVo.getTaskId());
            object.setProceeInstanceId(manageEntityVo.getProcessInstanceId());
            mapperapper.insert(object);
        }else { // 修改
            object.setId(his.getId());
            object.setOrderId(his.getOrderId());

            String processId = his.getProceeInstanceId();

            BeanUtils.copyProperties(object,his);

            his.setProceeInstanceId(processId);

            // 计算应付款 和 应付时间等
            if(his.getPaymentAmount()!=null){
                his = relaxPayAmount(his);
            }
            // 计算 结余款金额
            mapperapper.updateById(his);
            // 处理多余文件记录
            List<String> ids = new ArrayList<>();
            if((his.getFiels()!=null && his.getFiels().length()>0)){
                String temp = his.getFiels();
                String[] fieldIds = temp.split(",");
                ids =  Arrays.stream(fieldIds).collect(Collectors.toList());
            }
            if(StringUtils.isNotEmpty(his.getBusniessFile())){
                String temp = his.getBusniessFile();
                String[] fieldIds = temp.split(",");
                List<String> templIds =  Arrays.stream(fieldIds).collect(Collectors.toList());
                ids.addAll(templIds);
            }
            spFobFileRecordService.deleteOtherFileRecor(his.getId(),ids);
        }
    }

    public void createPayOrder(Long id){
        SpFobZfzzcdyfk his = this.getById(id);
        List<SpFobZfzzcdyfk> otherList = this.list(new LambdaQueryWrapper<SpFobZfzzcdyfk>().eq(SpFobZfzzcdyfk::getProceeInstanceId,his.getProceeInstanceId()).eq(SpFobZfzzcdyfk::getApprvalStatus,1));
        for(SpFobZfzzcdyfk his2:otherList){
            if(his2.getOrderId()==null){
                Long orderId = createPayOrder(his2.getProceeInstanceId(),his2);
                his2.setOrderId(orderId);
                this.updateById(his2);
            }
        }
    }


    @Override
    public SpFobBaseBean getBaseBeanByInstanceId(String id) {
        return mapperapper.selectOne(new LambdaQueryWrapper<SpFobZfzzcdyfk>().eq(SpFobZfzzcdyfk::getProceeInstanceId,id).ne(SpFobZfzzcdyfk::getStatus,-2));
    }
    @Override
    public void  saveEntity(SpFobBaseBean bean){
        SpFobZfzzcdyfk spFob = new SpFobZfzzcdyfk();
        BeanUtils.copyProperties(bean,spFob);
        this.save(spFob);
    }

    @Override
    public void updateEntityById(SpFobBaseBean bean) {
        SpFobZfzzcdyfk spFob = new SpFobZfzzcdyfk();
        BeanUtils.copyProperties(bean,spFob);
        this.updateById(spFob);
    }


    @Override
    public Object getFormData(String id,Long serviceId) {
        SpFobZfzzcdyfk spFobZzgcjr = null;
        if(serviceId!=null){
            spFobZzgcjr = mapperapper.selectById(serviceId);
        }else {
            spFobZzgcjr = mapperapper.selectOne(new LambdaQueryWrapper<SpFobZfzzcdyfk>().eq(SpFobZfzzcdyfk::getProceeInstanceId,id).ne(SpFobZfzzcdyfk::getStatus,-2));
        }
        if(spFobZzgcjr==null){
            return null;
        }
        if(StringUtils.isEmpty(spFobZzgcjr.getCostUnit())){
            spFobZzgcjr.setCostUnit("1");
        }
        Map<String,Object> map = JsonUtils.jsonToMap(JsonUtils.objectToJson(spFobZzgcjr), Object.class);
        if(StringUtils.isNotBlank(spFobZzgcjr.getFiels())){
            String[] ids = spFobZzgcjr.getFiels().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("fiels",spFobFileRecordList);
        }
        if(spFobZzgcjr.getBusniessFile()!=null){
            String[] ids = spFobZzgcjr.getBusniessFile().split(",");
            List<Long> resId = new ArrayList<>();
            for(String tempId:ids){
                if (StringUtils.isNotBlank(tempId)) {
                    resId.add(Long.parseLong(tempId));
                }
            }
            List<SpFobFileRecord> spFobFileRecordList =  spFobFileRecordService.listByIds(resId);
            map.put("busniessFile",spFobFileRecordList);
        }
        map.put("approvalStatus",spFobZzgcjr.getApprvalStatus());
        SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(spFobZzgcjr.getProceeInstanceId());
        if (execute.getExpectedLoadingPort()!=null && spFobZzgcjr.getPort() == null){
            map.put("port",execute.getExpectedLoadingPort());
        }
        if (spFobZzgcjr.getField3() == null) {
            map.put("field3", "否");
        }
        return map;
    }
    @Override
    public String  getTemplateParam(ManageEntityVo manageEntityVo) {
        ObjectNode json = manageEntityVo.getData();

        SpFobZfzzcdyfk spFobZzgcjr = JsonUtils.jsonToObject(JsonUtils.objectToJson(json),SpFobZfzzcdyfk.class);
        String  templateId = spFobZzgcjr.getTemplateId();
        if(templateId==null){
            throw  new BusException("请选模板后再生成模板正文", BaseResultCode.GENERAL_ERROR);
        }
        SpFobTemplate spFobTemplate = spFobTemplateService.getById(templateId);
        if(spFobTemplate == null){
            throw  new BusException("当前模板不存在，请联系管理员处理", BaseResultCode.GENERAL_ERROR);
        }
        Map<String,String> map = new HashMap<>();
        List<SpFobZzcbdl> zzcbdls = spFobZzcbdlService.list(new LambdaQueryWrapper<SpFobZzcbdl>().eq(SpFobZzcbdl::getProceeInstanceId,manageEntityVo.getProcessInstanceId()));
        if(zzcbdls.size()>0){
            Map<String,Object> tempMap = spFobZzcbdlService.findConShippingAgency(zzcbdls.get(0).getCronId());
            for(String key:tempMap.keySet()){
                String tempKey = JsonUtils.toCamelCase(key);
                map.put("conShippingAgency."+tempKey,tempMap.get(key)+"");
            }
            String tradeBody = null;
            if(tempMap.get("trade_body") instanceof Boolean){
                if(Boolean.valueOf(tempMap.get("trade_body")+"")){
                    tradeBody = "1";
                }
            }else {
                tradeBody = tempMap.get("trade_body")+"";
            }
            if("1".equals(tradeBody)){
                map.put("conShippingAgency.tradeBody","国贸");
            }else {
                map.put("conShippingAgency.tradeBody","新贸");
            }
        }
        // 调度方案信息
        SpDispatchSchemeExecute schemeDetail = schemeDetailService.getExceuteByInstanceId(manageEntityVo.getProcessInstanceId());
        if(schemeDetail!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(schemeDetail),String.class);
            for(String key:tempMap.keySet()){
                map.put("spDispatchSchemeDetail."+key,tempMap.get(key));
            }
            map.put("tempYear", CalculateDateUtil.getYears(schemeDetail.getExpectedLoadingDate()));
            map.put("tempmMonth", CalculateDateUtil.getMonths(schemeDetail.getExpectedLoadingDate()));
            map.put("tempDay", CalculateDateUtil.getDays(schemeDetail.getExpectedLoadingDate()));
        }
        // 当前业务表单信息
        if(json!=null){
            Map<String,String> tempMap = JsonUtils.jsonToMap(JsonUtils.objectToJson(json),String.class);
            for(String key:tempMap.keySet()){
                map.put("spFobZfzzcdyfk."+key,tempMap.get(key));
            }
            if(spFobZzgcjr.getPayAmount()!=null && spFobZzgcjr.getBalanceAmount()!=null){
                BigDecimal result = spFobZzgcjr.getPayAmount().subtract(spFobZzgcjr.getBalanceAmount());
                map.put("temp1",result.toString());
            }
            if(spFobZzgcjr.getPayDate()!=null){
                map.put("lastYear", CalculateDateUtil.getYears(spFobZzgcjr.getPayDate()));
                map.put("lastMonth", CalculateDateUtil.getMonths(spFobZzgcjr.getPayDate()));
                map.put("lastDay", CalculateDateUtil.getDays(spFobZzgcjr.getPayDate()));
            }
        }
        String template = "";
        if(spFobTemplate !=null){
            template = TemplateParamUtils.processDynamicParams(spFobTemplate.getContent(),map);
        }
        return template;
    }

    @Override
    public SpFobZfzzcdyfk findData(String processInstanceId) {
        SpFobZfzzcdyfk spFobZzgcjr = mapperapper.selectOne(new LambdaQueryWrapper<SpFobZfzzcdyfk>().eq(SpFobZfzzcdyfk::getProceeInstanceId,processInstanceId).ne(SpFobZfzzcdyfk::getStatus,-2));
        return spFobZzgcjr;
    }

    @Override
    public List<Long> findServieData(String processInstanceId){
        List<SpFobZfzzcdyfk> spFobBaseBeans =  mapperapper.selectList(new LambdaQueryWrapper<SpFobZfzzcdyfk>().eq(SpFobZfzzcdyfk::getProceeInstanceId,processInstanceId).orderByDesc(SpFobZfzzcdyfk::getCreateDate));
        List<Long> list = spFobBaseBeans.stream().map(SpFobBaseBean::getId).collect(Collectors.toList());
        return list;
    }

    @Autowired(required = false)
    ConFilesMapper conFilesMapper;
    @Autowired
    SpPaymentOrderService spPaymentOrderService;


    /**
     * 计算金额
     * @param his
     * @return
     */

    @Autowired(required = false)
    SpFundManageMapper spFundManageMapper;

    @Autowired(required = false)
    ConShippingAgencyMapper conShippingAgencyMapper;
    public SpFobZfzzcdyfk relaxPayAmount(SpFobZfzzcdyfk his){
        List<SpFobZzcbdl> zzcbdls = spFobZzcbdlService.list(
                new LambdaQueryWrapper<SpFobZzcbdl>()
                        .eq(SpFobZzcbdl::getProceeInstanceId,his.getProceeInstanceId())
                        .ne(SpFobZzcbdl::getStatus,-2)
                        .eq(StringUtils.isNotBlank(his.getPort()),SpFobZzcbdl::getPort,his.getPort())
        );
        //完成节点 增加 订单支付记录
        //spPaymentOrderService.
        // 合同关联信息正常
        if(zzcbdls!=null && zzcbdls.size()>0){
            SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(his.getProceeInstanceId());
            //Map<String, Object> tempMap = spFobZzcbdlService.findConShippingAgency(zzcbdls.get(0).getCronId());
            ConShippingAgency conShippingAgency = conShippingAgencyMapper.selectById(zzcbdls.get(0).getCronId());
            Integer tradeBody = 0;
            if(conShippingAgency !=null){
               tradeBody = conShippingAgency.getTradeBody();
            }
            String cnoocCorporation = null;
            if(conShippingAgency!=null){
                cnoocCorporation = conShippingAgency.getCompanyName();
            }

            if(StringUtils.isNotBlank(his.getField3()) && StringUtils.equals("是",his.getField3())){
                SpFundManage fundManageAdvance = spFundManageMapper.getFundManageAdvance(execute.getVoyageNo(), cnoocCorporation, tradeBody);
                if (null != fundManageAdvance && fundManageAdvance.getAccountBalance() != null) {
                    his.setBalanceYear(CalculateDateUtil.getYears(fundManageAdvance.getCreateDate()));
                    if(fundManageAdvance.getAccountBalance().compareTo(his.getPaymentAmount()) >= 0){
                        his.setBalanceAmount(his.getPaymentAmount());
                        his.setPayAmount(BigDecimal.ZERO);
                    }else{
                        his.setBalanceAmount(fundManageAdvance.getAccountBalance());
                        his.setPayAmount(his.getPaymentAmount().subtract(fundManageAdvance.getAccountBalance()));
                    }
                }else{
                    his.setBalanceAmount(BigDecimal.ZERO);
                    his.setBalanceYear(CalculateDateUtil.getYears(new Date()));
                    his.setPayAmount(his.getPaymentAmount());
                }
            }else{
                his.setBalanceAmount(BigDecimal.ZERO);
                his.setBalanceYear(CalculateDateUtil.getYears(new Date()));
                his.setPayAmount(his.getPaymentAmount());
            }

            //预付款时间（天）
            Integer advancePayDays = 0;
            //预付款时间类型1:工作日，2：自然日
            Integer advancePayType = 0;
            //结算时间（天）
            Integer payDays = 0;
            //结算时间类型1:工作日，2：自然日
            Integer payDaysType = 0;
            if (null != conShippingAgency) {
                advancePayDays = conShippingAgency.getAdvancePayDays();
                advancePayType = conShippingAgency.getAdvancePayDayType();
                payDays = conShippingAgency.getPayDays();
                payDaysType = conShippingAgency.getPayDaysType();
            }
            if (advancePayDays > 0) {
                Instant instant = execute.getExpectedLoadingDate().toInstant();
                ZoneId zoneId = ZoneId.systemDefault();
                LocalDate payEndTimeLocalDate = instant.atZone(zoneId).toLocalDate();
                payEndTimeLocalDate = payEndTimeLocalDate.minusDays(advancePayDays);
                //如果是工作日则判断，不是工作日不判断
                if (advancePayType > 0 && advancePayType.equals(1)) {
                    //判断是否是工作日  如果需要判断节假日查看辅助工具：6tail/lunar-java
                    DayOfWeek dayOfWeek = DayOfWeek.of(payEndTimeLocalDate.get(ChronoField.DAY_OF_WEEK));
                    switch (dayOfWeek) {
                        case SUNDAY:
                            payEndTimeLocalDate = payEndTimeLocalDate.minus(2, ChronoUnit.DAYS);
                        case SATURDAY:
                            payEndTimeLocalDate = payEndTimeLocalDate.minus(1, ChronoUnit.DAYS);
                    }
                }
                ZonedDateTime zdt = payEndTimeLocalDate.atStartOfDay(zoneId);
                his.setPayDate(Date.from(zdt.toInstant()));
            }

        }
        return his;
    }
    /**
     * 创建支付订单
     * @param processInstanceId
     * @param his
     */
    public Long createPayOrder(String processInstanceId,SpFobZfzzcdyfk his){
        List<SpFobZzcbdl> zzcbdls = spFobZzcbdlService.list(
                new LambdaQueryWrapper<SpFobZzcbdl>()
                        .eq(SpFobZzcbdl::getProceeInstanceId,processInstanceId)
                        .ne(SpFobZzcbdl::getStatus,-2)
                        .eq(StringUtils.isNotBlank(his.getPort()),SpFobZzcbdl::getPort,his.getPort())
        );
        //完成节点 增加 订单支付记录
        //spPaymentOrderService.
        // 合同关联信息正常
        if(zzcbdls!=null && zzcbdls.size()>0){
            SpDispatchSchemeExecute execute = schemeDetailService.getExceuteByInstanceId(processInstanceId);
            SpPaymentOrderBO spPaymentOrderBO = new SpPaymentOrderBO();
            spPaymentOrderBO.setContractId(Long.parseLong(zzcbdls.get(0).getCronId()));
            //装载港船预付款
            spPaymentOrderBO.setOrderType(1);
            //contractType  船舶代理
            spPaymentOrderBO.setContractType(1);
            spPaymentOrderBO.setPayAmount(his.getPaymentAmount());
            spPaymentOrderBO.setPayEndTime(his.getPlanEndDate());
            spPaymentOrderBO.setVoyageNo(execute.getVoyageNo());
            spPaymentOrderBO.setPayAmountUnit(1);
            spPaymentOrderBO.setOrderStatus(3);
            Map<String, Object> tempMap = spFobZzcbdlService.findConShippingAgency(zzcbdls.get(0).getCronId());
            if(tempMap!=null){
                spPaymentOrderBO.setContractName(tempMap.get("contract_name")+"");
            }
            List<ConFiles> conFiles = conFilesMapper.getConFilesByConIdAndFileType(Long.parseLong(zzcbdls.get(0).getCronId()),1);
            if(null !=conFiles && conFiles.size()>0){
                spPaymentOrderBO.setContractAddress(conFiles.get(0).getUrl());
            }

            List<BpmTaskDto> tasks = taskService.findActivitiOrFinishTaskResult(his.getOrderProcessId());
            // 封装用户信息
            if(tasks.size()>=2){
                SysUser user = remoteUserService.getUserByName(tasks.get(0).getAssigneeId());
                if(user!=null){
                    spPaymentOrderBO.setHandlePeople(user.getUserName());
                }
                SysUser user2 = remoteUserService.getUserByName(tasks.get(1).getAssigneeId());
                if(user2!=null){
                    spPaymentOrderBO.setApprovedPeople(user2.getUserName());
                }
            }else if(tasks.size()>=1){
                SysUser user = remoteUserService.getUserByName(tasks.get(0).getAssigneeId());
                if(user!=null){
                    spPaymentOrderBO.setHandlePeople(user.getUserName());
                    spPaymentOrderBO.setApprovedPeople(user.getUserName());
                }
            }
            SpPaymentOrder order = spPaymentOrderService.synchronousPayOrder(spPaymentOrderBO);
            //对于订单明细
            SpPaymentOrderDetailBO spPaymentOrderDetailBO = new SpPaymentOrderDetailBO();
            spPaymentOrderDetailBO.setOrderId(order.getId());
            spPaymentOrderDetailBO.setAdvancePayAmount(his.getPaymentAmount());
            spPaymentOrderDetailBO.setBalanceAmount(his.getBalanceAmount());
            spPaymentOrderDetailBO.setPayableAmount(his.getPayAmount());
            spPaymentOrderDetailBO.setIsSub(his.getField3());
            if(tempMap!=null){
                spPaymentOrderDetailBO.setShipAgencyCorporation(tempMap.get("company_name")+"");
            }
            String tradeBody = null;
            if(tempMap.get("trade_body") instanceof Boolean){
                boolean flag  = Boolean.valueOf(tempMap.get("trade_body")+"");
                if(flag){
                    tradeBody = "1";
                }else{
                    tradeBody = "2";
                }
            }
            if("1".equals(tradeBody)){
                spPaymentOrderDetailBO.setCnoocCorporation("CNOOC Gas and Power Trading& Marketing Limited");
            }else {
                spPaymentOrderDetailBO.setCnoocCorporation("CNOOC Gas and Power Singapore Trading& Marketing Pte. Ltd");
            }
            spPaymentOrderDetailBO.setShipName(execute.getShipName());
            spPaymentOrderDetailBO.setExpectedLoadingPort(execute.getExpectedLoadingPort());
            spPaymentOrderDetailBO.setExpectedLoadingDate(execute.getExpectedLoadingDate());
            spPaymentOrderDetailBO.setExpectedUnloadingDate(execute.getExpectedUnloadingWindow());
            spPaymentOrderDetailBO.setExpectedUnloadingPort(execute.getExpectedUnloadingPort());
            spPaymentOrderDetailBO.setBalanceAmount(his.getBalanceAmount());
            //实际装载时间
            /*String endDate = null;
            SpFobSyzlxzwj spFobSyzlxzwj = spFobSyzlxzwjService.findData(processInstanceId);
            if(spFobSyzlxzwj!=null && spFobSyzlxzwj.getUnloadDate()!=null){
                endDate = spFobSyzlxzwj.getUnloadDate().toString();
            }
            if(endDate==null){
                SpFobQrxzg data = spFobQrxzgService.findData(processInstanceId);
                if(data!=null && data.getExpectedUnloadingPort()!=null){
                    endDate = data.getExpectedUnloadingPort();
                }
            }
            if(endDate!=null){
                spPaymentOrderDetailBO.setRealityLoadingDate(CalculateDateUtil.pasrseDate(endDate));
            }*/
            spPaymentOrderDetailBO.setRealityLoadingDate(execute.getRealityLoadingDate());
            SpPaymentOrderDetail detail = spPaymentOrderService.synchronousPayOrderDetail(spPaymentOrderDetailBO);
            //同步资金管理
            SpFundManage fundManage = spPaymentOrderService.synchronousSpFundManage(order,detail);
            if(null != fundManage){
                //同步资金详情管理
                spPaymentOrderService.synchronousSpFundManageDetail(detail,fundManage.getId(),fundManage.getAccountBalance());
            }
            return order.getId();
        }
        return null;
    }

    @Resource
    @Lazy
    ProcessInstanceService processInstanceService;
    @Override
    public void startPostInstance(Long businessId,String key){
        SpFobZfzzcdyfk spFobZfzzcdyfk = this.getById(businessId);
        if(spFobZfzzcdyfk.getOrderProcessId()!=null && (spFobZfzzcdyfk.getApprvalStatus()==0 || spFobZfzzcdyfk.getApprvalStatus()==1)){
            throw new BusException("当前已发起审批，不可重复发起",BaseResultCode.GENERAL_ERROR);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("serviceType",key);
        map.put("moduleName","船运执行");
        map.put("reason","");
        String result = processInstanceService.createProcessInstance2(BpmInstanceService.SP_PAY_ORDER_EXISTS_BPM_KEY,map,businessId+"");
        spFobZfzzcdyfk.setOrderProcessId(result);
        spFobZfzzcdyfk.setApprvalStatus(0);
        spFobZfzzcdyfk.setCreateBy(SecurityUtils.getUsername());
        this.updateById(spFobZfzzcdyfk);
    }

    @Override
    public boolean checkApproveStatus(Long businessId) {
        SpFobZfzzcdyfk spFobZfzzcdyfk = this.getById(businessId);
        if(spFobZfzzcdyfk.getApprvalStatus()!=null && spFobZfzzcdyfk.getApprvalStatus()==1){
            return true;
        }
        return false;
    }

    @Resource
    @Lazy
    TaskService taskService;

    @Resource
    @Lazy
    RemoteUserService remoteUserService;

    @Resource
    WordUtil wordUtil;
    @Override
    @Transactional
    public void updateApprovaResult(Long businessId,Integer status){
        SpFobZfzzcdyfk spFobZfzzcdyfk = this.getById(businessId);
        if(status==1 && (StringUtils.isNotEmpty(spFobZfzzcdyfk.getField1()) || StringUtils.isNotEmpty(spFobZfzzcdyfk.getBusniessFile()))){ // 处理业务说明文件不为空，更新业务文件
           List<BpmTaskDto> tasks = taskService.findActivitiOrFinishTaskResult(spFobZfzzcdyfk.getOrderProcessId());
           Map<String,SysUser> map = new HashMap<>();
           // 封装用户信息
           if(tasks.size()>=1){
               SysUser user = remoteUserService.getUserByName(tasks.get(0).getAssigneeId());
               user.setCreateTime(tasks.get(0).getFinishTime());
               map.put("业务部门负责人：",user);
               String userName = "";
               if(tasks.size()>1){
                   userName = tasks.get(1).getAssigneeId();
                   if(userName==null) userName = SecurityUtils.getUsername();
                   SysUser user2 = remoteUserService.getUserByName(userName);
                   user2.setCreateTime(tasks.get(1).getFinishTime());
                   map.put("业务审核人：",user2);
               }else{
                   SysUser user2 = new SysUser();
                   BeanUtils.copyProperties(user,user2);
                   //user2.setCreateTime(tasks.get(0).getFinishTime());
                   map.put("业务审核人：",user2);
               }

               SysUser user3 = remoteUserService.getUserByName(spFobZfzzcdyfk.getCreateBy());
               user3.setCreateTime(spFobZfzzcdyfk.getCreateDate());
               map.put("业务经办人：",user3);
           }
           if(!map.isEmpty()){
               wordUtil.updateFileTemplate(businessId,spFobZfzzcdyfk.getField1(),map,spFobZfzzcdyfk.getBusniessFile());
           }
        }
        //记录状态
        spFobZfzzcdyfk.setApprvalStatus(status);
        this.updateById(spFobZfzzcdyfk);
    }

    public static String formatMoney(String money) {
        try{
            double m1 = Double.parseDouble(money);
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setMaximumFractionDigits(8); // 设置小数点后最多两位
            return numberFormat.format(m1);
        }catch (Exception e){
        }
        return money;
    }
}
